package com.example.shardingmultdatasource.config;

import com.zaxxer.hikari.HikariDataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;

import javax.sql.DataSource;
import java.util.HashMap;


/**
 * 数据源配置
 */
@Configuration
public class MultipleDataSourceConfig {

    @Autowired
    DBConfig dbConfig;



    @Primary
    @Bean(name = "dynamicDataSource")
    public DataSource dynamicDataSource() {
        DynamicDataSource dynamicDataSource = new DynamicDataSource();
        //配置默认数据源
        dynamicDataSource.setDefaultTargetDataSource(dbConfig.getDbs().get(0));

        //配置多数据源
        HashMap<Object, Object> dataSourceMap = new HashMap<>();
        dataSourceMap.put(ContextConst.DataSourceType.DB0.name(), dbConfig.getDbs().get(0));
        dataSourceMap.put(ContextConst.DataSourceType.DB1.name(), dbConfig.getDbs().get(1));
        dynamicDataSource.setTargetDataSources(dataSourceMap); // 该方法是AbstractRoutingDataSource的方法
        return dynamicDataSource;
    }

//
//    @Bean(name = "db0")
//    @ConfigurationProperties(prefix = "spring.datasource.db0")
//    public DataSource primaryDataSource() {
//        return new HikariDataSource();
//    }
//
//    @Bean(name = "db1")
//    @ConfigurationProperties(prefix = "spring.datasource.db1")
//    public DataSource localDataSource() {
//        return new HikariDataSource();
//    }
//
//    @Primary
//    @Bean(name = "dynamicDataSource")
//    public DataSource dynamicDataSource() {
//        DynamicDataSource dynamicDataSource = new DynamicDataSource();
//        //配置默认数据源
//        dynamicDataSource.setDefaultTargetDataSource(primaryDataSource());
//
//        //配置多数据源
//        HashMap<Object, Object> dataSourceMap = new HashMap<>();
//        dataSourceMap.put(ContextConst.DataSourceType.DB0.name(), primaryDataSource());
//        dataSourceMap.put(ContextConst.DataSourceType.DB1.name(), localDataSource());
//        dynamicDataSource.setTargetDataSources(dataSourceMap); // 该方法是AbstractRoutingDataSource的方法
//        return dynamicDataSource;
//    }
    /**
     * 配置@Transactional注解事务
     *
     * @return
     */
    @Bean
    public PlatformTransactionManager transactionManager() {
        return new DataSourceTransactionManager(dynamicDataSource());
    }
}